import { useState } from 'react'
import { Card, Table, Button, Space, Tag, Modal, message, Switch, Drawer, Form, Input, Select, TimePicker } from 'antd'
import { PlusOutlined, PlayCircleOutlined, PauseCircleOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons'
import './index.scss'

const { TextArea } = Input

const ScheduledTasks = () => {
  const [loading, setLoading] = useState(false)
  const [drawerVisible, setDrawerVisible] = useState(false)
  const [logVisible, setLogVisible] = useState(false)
  const [currentTask, setCurrentTask] = useState(null)
  const [form] = Form.useForm()

  // 模拟任务数据
  const [dataSource, setDataSource] = useState([
    {
      id: 1,
      name: '爬取豆瓣图书信息',
      type: 'crawler',
      schedule: '每天 02:00',
      status: 'running',
      lastRun: '2024-01-20 02:00:00',
      nextRun: '2024-01-21 02:00:00',
      successCount: 156,
      failCount: 2,
      description: '自动爬取豆瓣网站的图书信息，包括书名、作者、简介等',
    },
    {
      id: 2,
      name: '爬取图书评论',
      type: 'crawler',
      schedule: '每天 03:00',
      status: 'running',
      lastRun: '2024-01-20 03:00:00',
      nextRun: '2024-01-21 03:00:00',
      successCount: 89,
      failCount: 1,
      description: '爬取各大平台的图书评论和评分信息',
    },
    {
      id: 3,
      name: '数据清理任务',
      type: 'cleanup',
      schedule: '每周日 01:00',
      status: 'paused',
      lastRun: '2024-01-14 01:00:00',
      nextRun: '2024-01-21 01:00:00',
      successCount: 12,
      failCount: 0,
      description: '清理过期的临时数据和日志文件',
    },
    {
      id: 4,
      name: '数据备份任务',
      type: 'backup',
      schedule: '每天 00:00',
      status: 'running',
      lastRun: '2024-01-20 00:00:00',
      nextRun: '2024-01-21 00:00:00',
      successCount: 365,
      failCount: 0,
      description: '自动备份数据库数据',
    },
  ])

  // 任务类型配置
  const taskTypeConfig = {
    crawler: { text: '爬虫任务', color: 'blue' },
    cleanup: { text: '清理任务', color: 'orange' },
    backup: { text: '备份任务', color: 'green' },
    sync: { text: '同步任务', color: 'purple' },
  }

  // 状态配置
  const statusConfig = {
    running: { text: '运行中', color: 'success' },
    paused: { text: '已暂停', color: 'default' },
    error: { text: '错误', color: 'error' },
  }

  // 添加任务
  const handleAdd = () => {
    form.resetFields()
    setCurrentTask(null)
    setDrawerVisible(true)
  }

  // 编辑任务
  const handleEdit = (record) => {
    setCurrentTask(record)
    form.setFieldsValue(record)
    setDrawerVisible(true)
  }

  // 保存任务
  const handleSave = async (values) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      message.success(currentTask ? '任务更新成功' : '任务创建成功')
      setDrawerVisible(false)
    } catch (error) {
      message.error('操作失败')
    }
  }

  // 启动/暂停任务
  const handleToggleStatus = (record) => {
    const newStatus = record.status === 'running' ? 'paused' : 'running'
    setDataSource(prev =>
      prev.map(item =>
        item.id === record.id ? { ...item, status: newStatus } : item
      )
    )
    message.success(newStatus === 'running' ? '任务已启动' : '任务已暂停')
  }

  // 立即执行
  const handleRunNow = (record) => {
    Modal.confirm({
      title: '确认执行',
      content: `确定立即执行任务"${record.name}"吗？`,
      onOk: () => {
        message.success('任务已开始执行')
      },
    })
  }

  // 查看日志
  const handleViewLog = (record) => {
    setCurrentTask(record)
    setLogVisible(true)
  }

  // 删除任务
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定删除任务"${record.name}"吗？`,
      okType: 'danger',
      onOk: () => {
        setDataSource(prev => prev.filter(item => item.id !== record.id))
        message.success('删除成功')
      },
    })
  }

  const columns = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type) => (
        <Tag color={taskTypeConfig[type].color}>
          {taskTypeConfig[type].text}
        </Tag>
      ),
    },
    {
      title: '执行计划',
      dataIndex: 'schedule',
      key: 'schedule',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={statusConfig[status].color}>
          {statusConfig[status].text}
        </Tag>
      ),
    },
    {
      title: '上次执行',
      dataIndex: 'lastRun',
      key: 'lastRun',
      width: 160,
    },
    {
      title: '下次执行',
      dataIndex: 'nextRun',
      key: 'nextRun',
      width: 160,
    },
    {
      title: '成功/失败',
      key: 'count',
      width: 120,
      render: (_, record) => (
        <span>
          <span style={{ color: '#52c41a' }}>{record.successCount}</span>
          {' / '}
          <span style={{ color: '#ff4d4f' }}>{record.failCount}</span>
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={record.status === 'running' ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
            onClick={() => handleToggleStatus(record)}
          >
            {record.status === 'running' ? '暂停' : '启动'}
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => handleRunNow(record)}
          >
            立即执行
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewLog(record)}
          >
            日志
          </Button>
          <Button
            type="link"
            size="small"
            icon={<DeleteOutlined />}
            danger
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="scheduled-tasks-container">
      <Card className="tasks-card">
        <div className="tasks-header">
          <div>
            <h3>定时任务管理</h3>
            <p>管理系统的定时任务，包括爬虫任务、数据清理等</p>
          </div>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新建任务
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          loading={loading}
          pagination={{
            total: dataSource.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新建/编辑任务抽屉 */}
      <Drawer
        title={currentTask ? '编辑任务' : '新建任务'}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            label="任务名称"
            name="name"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>

          <Form.Item
            label="任务类型"
            name="type"
            rules={[{ required: true, message: '请选择任务类型' }]}
          >
            <Select placeholder="请选择任务类型">
              <Select.Option value="crawler">爬虫任务</Select.Option>
              <Select.Option value="cleanup">清理任务</Select.Option>
              <Select.Option value="backup">备份任务</Select.Option>
              <Select.Option value="sync">同步任务</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="执行计划"
            name="schedule"
            rules={[{ required: true, message: '请输入执行计划' }]}
          >
            <Input placeholder="例如：每天 02:00" />
          </Form.Item>

          <Form.Item
            label="任务描述"
            name="description"
          >
            <TextArea rows={4} placeholder="请输入任务描述" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setDrawerVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>

      {/* 执行日志抽屉 */}
      <Drawer
        title="执行日志"
        width={800}
        open={logVisible}
        onClose={() => setLogVisible(false)}
      >
        <div className="log-content">
          <div className="log-item">
            <span className="time">2024-01-20 02:00:00</span>
            <Tag color="success">成功</Tag>
            <span className="message">任务执行成功，爬取了120条数据</span>
          </div>
          <div className="log-item">
            <span className="time">2024-01-19 02:00:00</span>
            <Tag color="success">成功</Tag>
            <span className="message">任务执行成功，爬取了115条数据</span>
          </div>
          <div className="log-item">
            <span className="time">2024-01-18 02:00:00</span>
            <Tag color="error">失败</Tag>
            <span className="message">网络连接超时</span>
          </div>
        </div>
      </Drawer>
    </div>
  )
}

export default ScheduledTasks
